<?php

namespace App\Jobs\Tcm;

use App\Constants\VipOrderStatusConstant;
use App\Models\MemberVipOrder;
use App\Models\TcmBook;
use App\Models\TcmBookCollect;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class InitMemberBookCollect implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $memberIdArr;

    public function __construct(array $memberIdArr)
    {
        $this->memberIdArr = $memberIdArr;
    }

    public function handle()
    {
        $memberIdArr = $this->memberIdArr;

        if (!$memberIdArr) return;

        // 首次初始化书架9本有声小说
        $bookIds = TcmBook::where('status', 1)->where('sound', 1)->limit(9)->pluck('id')->all();
        if (!$bookIds) return;

        $data = [];

        foreach ($memberIdArr as $memberId) {
            $exists = TcmBookCollect::where('member_id', $memberId)->exists();
            if ($exists) continue;

            foreach ($bookIds as $bookId) {
                $data[] = ['member_id' => $memberId, 'book_id' => $bookId];
            }
        }

        TcmBookCollect::insert($data);
    }
}
